import utils.JDBCUtil01;
import utils.JDBCUtil01;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        //获取表单提交的数据
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        boolean loginSuccess=false;
        try {
            //获取连接
            conn=JDBCUtil01.getConnection();
            String sql="select * from t_user where username=? and password=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            rs=ps.executeQuery();
            if(rs.next()){
                loginSuccess=true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            JDBCUtil01.close(conn,ps,rs);
        }
        if (loginSuccess){
            //登录成功判断是否勾选了三天内免登录
            //首先获取勾选按钮的值进行判断
            String NotLogin=request.getParameter("NotLogin");
            if ("OK".equals(NotLogin)) {
                //判断为真则创建cookie对象
                Cookie cookie1 = new Cookie("username", username);
                Cookie cookie2 = new Cookie("password", password);
                //设定cookie的三天有效时间
                cookie1.setMaxAge(60 * 60 * 24 * 3);
                cookie2.setMaxAge(60 * 60 * 24 * 3);
                //设定cookie的关联路径
                cookie1.setPath(request.getContextPath());
                cookie2.setPath(request.getContextPath());
                //发送cookie
                response.addCookie(cookie1);
                response.addCookie(cookie2);
            }
            response.sendRedirect(request.getContextPath()+"/Main.html");
        }else{
            response.sendRedirect(request.getContextPath()+"/LoginError.html");
        }
    }
}
